package com.example.demo.arithmetic.datastructure.linkedlist2;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

// 给定一个已排序的链表的头 head ，
// 删除原始链表中所有重复数字的节点，只留下不同的数字 。返回 已排序的链表
// 输入：head = [1,2,3,3,4,4,5]
//输出：[1,2,5]
//输入：head = [1,1,1,2,3]
//输出：[2,3]
public class Leetcode82 {
    public static void main(String[] args) {
        ListNode head1 = new ListNode(3, null);
        ListNode head2 = new ListNode(2, head1);
        ListNode head3 = new ListNode(1, head2);
        ListNode head4 = new ListNode(1, head3);
        ListNode head5 = new ListNode(1, head4);
        ListNode head = new Leetcode82().deleteDuplicates2(head5);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        if (head.val == head.next.val) {
            ListNode x = head.next.next;
            while (x != null && x.val == head.next.val) {
                x = x.next;
            }
            return deleteDuplicates(x);
        } else {
            head.next = deleteDuplicates(head.next);
            return head;
        }
    }

    public ListNode deleteDuplicates2(ListNode head) {
        if (head == null) {
            return head;
        }

        ListNode dummy = new ListNode(0, head);

        ListNode cur = dummy;
        while (cur.next != null && cur.next.next != null) {
            if (cur.next.val == cur.next.next.val) {
                int x = cur.next.val;
                while (cur.next != null && cur.next.val == x) {
                    cur.next = cur.next.next;
                }
            } else {
                cur = cur.next;
            }
        }

        return dummy.next;
    }

//    作者：力扣官方题解
//    链接：https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/solutions/678122/shan-chu-pai-xu-lian-biao-zhong-de-zhong-oayn/
//    来源：力扣（LeetCode）
//    著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。


    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
